package com.itheima.tlias.filter;

import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;

import java.io.IOException;

//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		//获取url
		String url = request.getRequestURI();

		//判断是否包含login
		if (url.contains("login")) {
			filterChain.doFilter(request, response);
			return;
		}
		//获取jwt
		String jwt = request.getHeader("token");
		if (jwt == null || jwt.isEmpty()) {
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
			return;
		}

		//验证token
		try {
			Claims claims = JwtUtils.parseJWT(jwt);
		} catch (Exception e) {
			response.setStatus(HttpStatus.SC_UNAUTHORIZED);
			return;
		}

		//放行
		filterChain.doFilter(request, response);

	}

	@Override
	public void destroy() {

	}
}
